import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/utils/encrypt.dart';
import 'package:universal_html/html.dart' as uhtml;

mixin CacheManager {
  Map<String, String>? cookies;
  Future<bool> saveToken(String? username, String? token, String? role) async {
    final box = Hive.box('appconfig');
    box.put(CacheManagerKey['username'].toString(), username);
    box.put(CacheManagerKey['authtoken'].toString(), token);
    box.put(CacheManagerKey['nanhairole'].toString(), role);
    return true;
  }

  String? getUsername() {
    final box = Hive.box('appconfig');
    return box.get(CacheManagerKey['username'].toString());
  }

  String? getToken() {
    final box = Hive.box('appconfig');
    return box.get(CacheManagerKey['authtoken'].toString());
  }

  String? getRole() {
    final box = Hive.box('appconfig');
    return box.get(CacheManagerKey['nanhairole'].toString());
  }

  String? getWebUsername() {
    cookies = Map();
    var cookString = uhtml.document.cookie;
    String? _userName;
    if (cookString != null && cookString.contains(';')) {
      final entity = cookString.split("; ").map((item) {
        int idx = item.indexOf("=");
        List<String> split = [
          item.substring(0, idx).trim(),
          item.substring(idx + 1).trim()
        ];
        return MapEntry(split[0].trim(), split[1].trim());
      });
      cookies = Map.fromEntries(entity);
    }

    if (cookies!.containsKey('nanhaiV4.8Role')) {
      String role = cookies?['nanhaiV4.8Role'] ?? '';
      switch (role) {
        case Constants.NanhaiRole_Student:
          _userName = cookies!['nanhaiV4.8StudentUserId'] ?? '';
          break;
        case Constants.NanhaiRole_Individual:
          _userName = cookies!['nanhaiV4.8IndividualUserId'] ?? '';
          break;
        case Constants.NanhaiRole_SchoolAdmin:
          _userName = cookies!['nanhaiV4.8SchooladminUserId'] ?? '';
          break;
        case Constants.NanhaiRole_Teacher:
          _userName = cookies!['nanhaiV4.8TeacherUserId'] ?? '';
          break;
        default:
          _userName = '';
          break;
      }
    } else {
      _userName = '';
    }
    return _userName;
  }

  String? getWebToken() {
    String? _authToken;
    if (cookies!.containsKey('nanhaiV4.8Role')) {
      String role = cookies?['nanhaiV4.8Role'] ?? '';
      switch (role) {
        case Constants.NanhaiRole_Student:
          _authToken = cookies!['nanhaiV4.8StudentSession'] ?? '';
          break;
        case Constants.NanhaiRole_Individual:
          _authToken = cookies!['nanhaiV4.8IndividualSession'] ?? '';
          break;
        case Constants.NanhaiRole_SchoolAdmin:
          _authToken = cookies!['nanhaiV4.8SchooladminSession'] ?? '';
          break;
        case Constants.NanhaiRole_Teacher:
          _authToken = cookies!['nanhaiV4.8TeacherSession'] ?? '';
          break;
        default:
          _authToken = '';
      }
    } else {
      _authToken = '';
    }
    return _authToken;
  }

  String? getWebRole() {
    if (cookies!.containsKey('nanhaiV4.8Role')) {
      return cookies?['nanhaiV4.8Role'] ?? '';
    } else {
      return '';
    }
  }

  Future<bool> saveCurrentClass(String classId) async {
    final box = Hive.box('appconfig');
    box.put(CacheManagerKey['currentclass'].toString(), classId);
    return true;
  }

  String? getCurrentClass() {
    final box = Hive.box('appconfig');
    return box.get(CacheManagerKey['currentclass'].toString());
  }

  String? getCurrentClassPrograms() {
    final box = Hive.box('appconfig');
    return box.get(CacheManagerKey['currentclassProgramId'].toString());
  }

  Future<bool> savePassword(String password) async {
    EncryptData.encryptAES(password);
    final box = Hive.box('appconfig');
    box.put(
        CacheManagerKey['password'].toString(), EncryptData.encrypted?.base64);
    return true;
  }

  Future<bool> removePassword() async {
    final box = Hive.box('appconfig');
    box.delete(CacheManagerKey['password'].toString());
    return true;
  }

  Future<bool> saveProfileSettings(String profileSettings) async {
    final box = Hive.box('appconfig');
    box.put(CacheManagerKey['profilesettings'].toString(), profileSettings);
    return true;
  }

  Future<bool> removeProfileSettings() async {
    final box = Hive.box('appconfig');
    box.delete(CacheManagerKey['profilesettings'].toString());
    return true;
  }

  String? getProfileSettings() {
    final box = Hive.box('appconfig');
    return box.get(CacheManagerKey['profilesettings'].toString());
  }

  String? getProfile() {
    final box = Hive.box('appconfig');
    return box.get('UserProfile');
  }

  // Future<void> removeToken() async {
  //   //final box = Hive.box('appconfig');
  //   //box.delete(CacheManagerKey['currentclass'].toString());
  //   //box.delete(CacheManagerKey['profilesettings'].toString());
  //   //box.delete(CacheManagerKey['currentclassProgramId'].toString());
  // }
}

const Map<String, String> CacheManagerKey = {
  'authtoken': 'authtoken',
  'nanhairole': 'nanhairole',
  'username': 'username',
  'password': 'password',
  'currentclass': 'currentclass',
  'currentclassdetails': 'currentclassdetails',
  'currentclassProgramId': 'currentclassProgramId',
  'profilesettings': 'profilesettings',
  'darkmode': 'darkmode',
  'locale': 'locale',
  'eveluationlevel': 'eveluationlevel',
  '_audio': '_audio',
  '_auto': '_auto',
  '_pinyin': '_pinyin',
  '_text': '_text',
  '_viewMode': '_viewMode',
  '_quizAvailable': '_quizAvailable',
  '_readComplete': '_readComplete',
  '_callEva': '_callEva',
  '_isFinished': '_isFinished',
  '_readingType': '_readingType',
  'interfaceChinese': 'interfaceChinese'
};
